package cn.rui.service.impl;

import cn.rui.common.Content;
import cn.rui.common.Result;
import cn.rui.mapper.PermissionMapper;
import cn.rui.mapper.UserPermissionMapper;
import cn.rui.pojo.Permission;
import cn.rui.pojo.UserPermission;
import cn.rui.service.PermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 徽州大都督
 * @date 2021/05/14
 */
@Service
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private UserPermissionMapper userPermissionMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<String> findByUserUuid(String uuid) {

        List<String> permissionList = permissionMapper.findByUserUuid (uuid);

        return permissionList;
    }

    @Override
    public List<Permission> findPermission() {

        List<Permission> permissionList = permissionMapper.selectList (null);
        return permissionList;
    }

    @Override
    public List<Integer> findByUserUuids(String uuid) {

        List<Integer> permissionIds= permissionMapper.findPermissionId(uuid);
        return permissionIds;
    }

    @Override
    public Result editPermissionByUUid(List<Integer> permissionIds, String uuid) {

        QueryWrapper<UserPermission> wrapper = new QueryWrapper<> ();
        //wrapper.in ("permission_id",permissionIds);
        wrapper.eq ("user_uuid",uuid);
        userPermissionMapper.delete (wrapper);

        for (Integer permissionId : permissionIds) {
            UserPermission userPermission = new UserPermission ();
            userPermission.setPermissionId (permissionId);
            userPermission.setUserUuid (uuid);
            userPermissionMapper.insert (userPermission);
        }

        //删除缓存
        if (redisTemplate.hasKey (Content.PERMISSION_CODE + uuid)){
            redisTemplate.delete (Content.PERMISSION_CODE + uuid);
        }

        return Result.getSuccess ("修改成功!");
    }

}
